import React, { useState, useEffect,useRef } from "react";
import LlxTable from 'components/LlxTable'
import LlxForm from 'components/LlxForm/index'
import { Form ,Button,notification,Select,Divider,DatePicker,Tag,Modal,message} from 'antd';
import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries} from 'redux/action'

import { Menu, Dropdown, Space} from 'antd';
import { DownOutlined ,ExclamationCircleOutlined} from '@ant-design/icons'

import {updateUpperLowerBatchTheme,getThemePackagePublish,getThemePackage,editThemeStatusBatch,editThemeBatch,pushPool} from 'api/index'
import classNames from "classnames";

// 新增弹框 

import TaskAllocation from "components/Operations/task";

import ChangeStatus from "components/Operations/status";
import PreviewWordSubject from "components/LlxPreview/afterPreview";



const { RangePicker } = DatePicker;
const { confirm } = Modal;

const AddTheme = (props) => {
  const {isModalVisible,setIsModalVisible,dictionaries} = props

  const [form] = Form.useForm();
 

  const newThemeItem = [
    {label: '课程名称',type:'input', name: 'lessonName',rules:[
      {
        required: true,
        message: '请输入绘本名称'
      },
    ], span: 12 },
    {label: '级别', name: 'levelId', span: 12,rules:[
      {
        required: true,
        message: '请选择级别'
      },
    ],render: () => {
      return <Select
      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'id',label:'dictValue'}}
      placeholder={'请选择级别'}
      options={dictionaries.Level}
 >
 </Select> }},
    {label: '课程ID',type:'input', name: 'lessonCode', span: 12 },
    {label: '词汇',type:'textArea', name: 'words', span: 12 },
    {label: '课程目标',type:'textArea', name: 'remark', span: 12 },
    {label: '句型',type:'textArea', name: 'sentencePattern', span: 12 },
    {label: '拼读词汇',type:'textArea', name: 'lessonReading', span: 12 },
    {label: '字母',type:'textArea', name: 'letter', span: 12 },
    {label: '主题曲',type:'textArea', name: 'themeAudio', span: 12 },
  ]



  const handleCancel = () => {
    setIsModalVisible(false)
  }

  const handleOk = () => {
    form.validateFields().then(async()=>{

      const data = form.getFieldValue()

      console.log(data);

      message.success('新增成功')

      setIsModalVisible(false)
     
    }).catch(err=>{
      message.error('新增失败,请检查必填项,或稍后重试');
    })
  }


  return  <Modal width={950} title="新增主题课" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
  <LlxForm form={form} labelCol={5} formItem={newThemeItem} />
</Modal>
}


const formItems = (dictionaries,getUpdateTime) => {
  return [
      {label: '名称',type:'input', name: 'lessonName', span: 4 },
      {label: '状态', name: 'lessonStatus', span: 5 ,render: () => {
      return <Select
      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'dictValue',label:'dictValue'}}
      placeholder={'请选择状态'}
      options={dictionaries.wordStatus}
    >
    </Select>
      }},
      {label: '上下架', name: 'shelf', span: 5 ,render: () => {
         return <Select
         allowClear
         optionFilterProp="id"
         showSearch
         fieldNames={{value:'id',label:'dictValue'}}
         placeholder={'请选择上下架状态'}
         options={dictionaries.Publish}
      >
      </Select>
      }},
      {label: '级别', name: 'levelId', span: 5,render: () => {
        return <Select
        allowClear
        optionFilterProp="dictValue"
        showSearch
        fieldNames={{value:'id',label:'dictValue'}}
        placeholder={'请选择级别'}
        options={dictionaries.Level}
   >
   </Select> }},
      {label: '题数', name: 'subjectCount', span: 5,render: () => {
        return <Select
        allowClear
        optionFilterProp="dictValue"
        showSearch
        fieldNames={{value:'id',label:'dictValue'}}
        placeholder={'请选择题数'}
      options={dictionaries.CountNumber}
   >
   </Select> }},
      {label: '课程ID',type:'input', name: 'lessonCode', span: 5 },
      {label: '词汇',type:'input', name: 'words', span: 4 },
      {label: '目标描述',type:'input', name: 'remark', span: 5 },
      {label: '句型',type:'input', name: 'sentencePattern', span: 5 },
      {label: '拼读单词',type:'input', name: 'lessonReading', span: 5 },
      {label: '字母',type:'input', name: 'letter', span: 5 },
      {label: '创建人', name: 'createBy',  span: 4 ,render: () => {
         return <Select
         allowClear
         optionFilterProp="userName"
         showSearch
         fieldNames={{value:'userName',label:'userName'}}
         placeholder={'请选择创建人'}
      options={dictionaries.UserSpecies}
    >
    </Select>
      }},
        {label: '负责人', name: 'manager',  span: 5,render: () => {
        return <Select
        allowClear
        optionFilterProp="userName"
        showSearch
        fieldNames={{value:'userName',label:'userName'}}
        placeholder={'请选择负责人'}
        options={dictionaries.UserSpecies}
      >
      </Select>
      }},
        {label: '更新人', name: 'updateBy',  span: 5,render: () => {
        return <Select
        allowClear
        optionFilterProp="userName"
        showSearch
        fieldNames={{value:'userName',label:'userName'}}
      placeholder={'请选择更新人'}
      options={dictionaries.UserSpecies}
    >
    </Select>
      }},
       {label: '更新时间', name: 'updateTime', span: 5 ,render: () => {
      return  <RangePicker showTime onChange={getUpdateTime} style={{width:'100%'}}/>
      }}
  ]
}

function ThemeLibrary(props) {
const {dictionaries} = props
// 数据
const [loading,setLoading] = useState(false) //加载
const [expand,setExpand] = useState(false) //表单伸缩
const [total,setTotal] = useState(0) //总数量
const [id,setId] = useState('') //总数量
const [isModalVisible, setIsModalVisible] = useState(false)
const [isModalVisiblePreview, setIsModalVisiblePreview] = useState(false)
const [isModalVisibleTask, setIsModalVisibleTask] = useState(false)
const [isModalVisibleStatus, setIsModalVisibleStatus] = useState(false)
const [selectData, setSelectData] = useState([])
const [form] = Form.useForm();//搜索列表
//选择数据
const [selectedRowKeys,setselectedRowKeys] = useState([])
const rowSelection  = useRef({
  selectedRowKeys: selectedRowKeys,
  onChange: value => {
  setselectedRowKeys(value)
  rowSelection.current.selectedRowKeys = value
  }
})

// 7.获取时间
const getUpdateTime = (value,dataString) => {
  const data = form.getFieldValue()
  data.startTime=dataString[0]
  data.endTime=dataString[1]
  form.setFieldsValue(data)
}


// 表单数据
const formItem = !props.examineStatus?formItems(dictionaries,getUpdateTime).filter(i=>!['上下架'].includes(i.label)):formItems(dictionaries,getUpdateTime).filter(i=>!['状态','负责人'].includes(i.label))
//分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:20
})
//初始表格数据
const [dataSource,setDataSource] = useState([])
//表头配置信息
const columns = !props.examineStatus?[
      {title: '序号',fixed:'left',  dataIndex: 'sort', key: 'sort', align: 'center',width:50},
      {title: '名称',fixed:'left', dataIndex: 'lessonName',width:150, key: 'lessonName', align: 'center',render: (text, record) => {
        return <div className="operate_link_group text-nowrap text-link" onClick={()=>goThemeInfo(record.id)}>
          {text}
       </div>
     }},
      {title: '级别', dataIndex: 'levelName',width:60, key: 'levelName', align: 'center'},
      {title: '状态', dataIndex: 'lessonStatus',width:60, key: 'lessonStatus', align: 'center'},
      {title: '课程ID', dataIndex: 'lessonCode',width:150, key: 'lessonCode', align: 'center'},
      {title: '字母', dataIndex: 'letter',width:100, key: 'letter', align: 'center'},
      {title: '词汇', dataIndex: 'words',width:150, key: 'words', align: 'center'},
      {title: '题数', dataIndex: 'count',width:50, key: 'count', align: 'center'},
      {title: '拼读单词', dataIndex: 'lessonReading',width:150, key: 'lessonReading', align: 'center'},
      {title: '句型', dataIndex: 'sentencePattern',width:150, key: 'sentencePattern', align: 'center'},
      {title: '目标描述', dataIndex: 'remark',width:150, key: 'remark', align: 'center'},
      {title: '创建人',width:120, dataIndex: 'createBy', key: 'createBy', align: 'center',render: (text, record) => {
        return <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
          {text}
       </div>
      }},
      {title: '负责人',width:120, dataIndex: 'manager', key: 'manager', align: 'center', render: (text, record) => {
        return <div className={classNames((props.userInfo.user.userName===record.qmanager)||(props.userInfo.user.userName===record.rmanager)?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
        {record.qmanager||record.rmanager}
       </div>
      }},
      {title: '更新人',width:120, dataIndex: 'updateBy', key: 'updateBy', align: 'center',render: (text, record) => {
        return  <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
        {text}
     </div>
      }},
      {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:150},
      {title: '操作',fixed:'right', dataIndex: 'active', key: 'active', align: 'center',width:100,render:(text, record) => {
        return  <>
         <span className="text-link" onClick={()=>previewSubject(record)}>预览</span>&nbsp;&nbsp;&nbsp;
        </>
      }}
    ]:[
      {title: '序号',fixed:'left',  dataIndex: 'sort', key: 'sort', align: 'center',width:50},
      {title: '名称',fixed:'left', dataIndex: 'lessonName',width:250, key: 'lessonName', align: 'center',render: (text, record) => {
           return <div className="operate_link_group text-nowrap text-link" onClick={()=>goThemeInfo(record.id)}>
             {text}
          </div>
     }},
     {title: '上下架状态', dataIndex: 'upperLowerName', key: 'upperLowerName',width:100, align: 'center', render: (text, record) => {
          return <div className="operate_link_group text-nowrap">
           {
            text==='已上架'?<Tag  color="success">{text}</Tag>:<Tag  color="red">{text}</Tag>
           }
        </div>}},
      {title: '课程ID', dataIndex: 'lessonCode',width:150, key: 'lessonCode', align: 'center'},
      {title: '字母', dataIndex: 'letter',width:150, key: 'letter', align: 'center'},
      {title: '词汇', dataIndex: 'words',width:150, key: 'words', align: 'center'},
      {title: '题数', dataIndex: 'count',width:150, key: 'count', align: 'center'},
      {title: '拼读单词', dataIndex: 'lessonReading',width:150, key: 'lessonReading', align: 'center'},
      {title: '句型', dataIndex: 'sentencePattern',width:150, key: 'sentencePattern', align: 'center'},
      {title: '目标描述', dataIndex: 'remark',width:150, key: 'remark', align: 'center'},
      {title: '级别', dataIndex: 'levelName',width:100, key: 'levelName', align: 'center'},
      {title: '创建人',width:120, dataIndex: 'createBy', key: 'createBy', align: 'center',render: (text, record) => {
        return <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
          {text}
       </div>
      }},
      {title: '负责人',width:120, dataIndex: 'manager', key: 'manager', align: 'center', render: (text, record) => {
        return <div className={classNames((props.userInfo.user.userName===record.qmanager)||(props.userInfo.user.userName===record.rmanager)?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
        {record.qmanager||record.rmanager}
       </div>
      }},
      {title: '更新人',width:120, dataIndex: 'updateBy', key: 'updateBy', align: 'center',render: (text, record) => {
        return  <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
        {text}
     </div>
      }},
      {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:150},
      {title: '操作',fixed:'right', dataIndex: 'active', key: 'active', align: 'center',width:100,render:(text, record) => {
        return  <>
         <span className="text-link" onClick={()=>previewSubject(record)}>预览</span>&nbsp;&nbsp;&nbsp;
        </>
      }}
    ]
     
     
// 初始化
//1缓存页面数据 缓存表单数据
useEffect(()=>{
  form.setFieldsValue(props.tabList.filter(i=>i.url==='plan/courseSubject')[0]?.data?.form)
  setPagination(props.tabList.filter(i=>i.url==='plan/courseSubject')[0]?.data?.pagination||{
    current:1,
    pageSize:20
  })
  },[]) // eslint-disable-line react-hooks/exhaustive-deps


// 切换发布草稿素材
useEffect(()=>{
  // 获取数据
  getNewList()

  
},[props.examineStatus]) // eslint-disable-line react-hooks/exhaustive-deps

// 方法
// 1.获取数据
const getNewList=(value)=>{
  // 清空选中状态
   setselectedRowKeys(()=>[])
   rowSelection.current.selectedRowKeys=[]

   setLoading(true)

  // 缓存数据
   const data = {
     pagination: value&&value.pageSize?value:pagination,
     form:form.getFieldValue()
  }
    props.setPageDataFn('plan/courseSubject',data) 

    const initialData = async () => {
      const params = form.getFieldValue()
      params.currPage=value&&value.pageSize?value.current:pagination.current
      params.pageSize=value&&value.pageSize?value.pageSize:pagination.pageSize
    

      if (params.subjectCount === 0 || params.subjectCount) {
        params.countBg = params.subjectCount
        params.countEd = params.subjectCount !== 50 ? params.subjectCount + 5 : 1000
      }

      if(!props.examineStatus){
      
        const res = await getThemePackage(params)
        const data = res.result.records || []

        data.forEach((i,y)=>{
          i.sort =value&&value.pageSize?value.pageSize * (value.current - 1) + y + 1:pagination.pageSize * (pagination.current - 1) + y + 1
        })
        

        setDataSource(data)
  
        setTotal(res.result.total)

        
      } else {
        if (params.shelf === 1) {
          params.upperLower = 1010
        } else if (params.shelf === 2) {
          params.upperLower = 1000
        } else {
          params.upperLower = ''
        }

        const res = await getThemePackagePublish(params)
        const data = res.result.records || []
        
        data.forEach((i,y)=>{
          i.sort =value&&value.pageSize?value.pageSize * (value.current - 1) + y + 1:pagination.pageSize * (pagination.current - 1) + y + 1
        })
        

        setDataSource(data)
  
        setTotal(res.result.total)
      }
    

      setLoading(false)
    
    }
  
    initialData()
 }
 // 2.重置表单
 const resetForm=()=>{
   form.resetFields()
   setPagination({
    current:1,
    pageSize:20
  })
   getNewList()
 }
//  3.预览课后题和单词
const previewSubject = (value) => {
  setId(value.id)
  setIsModalVisiblePreview(true)
}
//  4.主题课详情
const goThemeInfo = (id) => {
props.history.push('/view/plan/themeSubjectInfo?id=' + id)
props.addRouter({
  menuName:'主题课详情',url:'plan/themeSubjectInfo?id=' + id 
})
}
//  5.新增主题课
const addNewTheme = () => {
  setIsModalVisible(true)
}
//  6.更多操作
const moreOperation = (value) =>{
  // 判断是否选择了数据
  if(!selectedRowKeys.length){
    notification.warning({
      message: '请至少选择一项数据',
      duration:1.5
    });
    return
  }
  
  const data = dataSource.filter((i)=>selectedRowKeys.includes(i.id))

  setSelectData(dataSource.filter((i)=>selectedRowKeys.includes(i.id)))

  switch (value.key) {
     case 'taskOther':
     //  分配任务
     if(data.some(i=>i.lessonStatus==='P')){
       notification.warning({
         message: '你的选择中含有已发布的数据，请重新选择',
         duration:1.5
       });
       return
     }
     setIsModalVisibleTask(true)
     break
     case 'statusCheck':
      //  修改状态
      setIsModalVisibleStatus(true)
     break
     case 'pushTestArea':
       //  添加到测试区
       confirm({
         title: '是否将选中的数据添加到测试区',
         icon: <ExclamationCircleOutlined />,
         onOk() {
          const http = async()=>{
           await pushPool({
             dataId: data.map(i => i.id),
             levelId: 255,
             poolId: 609,
             type: 'LESSON'
           })
 
           notification.success({
             message: '添加成功',
             duration:1.5
           });
             // 清空选中状态
           getNewList()
          }
 
          http()
         },
         onCancel() {
           // 取消
         },
       });
      break
      case 'upperAndLower': 
       // 判断选择的是否同一种数据
       const value = data[0].upperLower
       if (data.filter(i => i.upperLower !== value).length) {
        message.error('请选择同一状态的数据')
        return
      }
       // 上下架操作
       confirm({
        title: '你确定要选择上架或者下架嘛?',
        icon: <ExclamationCircleOutlined />,
        okText: '确定',
        cancelText: '取消',
        async onOk() {
          // 修改数据接口请求
           
          await updateUpperLowerBatchTheme({
            ids: data.map(i => i.id),
            upperLower: value === 1010 ? 1000 : 1010
          })
           
          getNewList()
  
          notification.success({
            message: '操作成功',
            description: '操作人：' + props.userInfo.user.userName,
            duration:1
          });
        },
        onCancel() {
        },
      });
      break
    default:
      return
   }

}
// 6.1.更多操作
const menu = (
 <Menu
    onClick={moreOperation}
    items={props.userBtnRole.includes('BOOK_BUTTON_ONE')?[
      {
        label: '任务分配',
        key: 'taskOther',
      },
      {
        label: '状态退回',
        key: 'statusCheck',
      },
      {
        label: '添加至测试区',
        key: 'pushTestArea',
      }
    ]:[
      {
        label: '添加至测试区',
        key: 'pushTestArea',
      }
    ]}
  />
);



return <div className="app-content animate__animated animate__fadeIn">
    {/* 表单 */}
    <LlxForm form={form} formItem={expand?formItem:formItem.filter((i,j)=>j<5)}/>
    {/* 操作按钮 */}
    <div className="operate-btn">
     <div>
       {
          !props.examineStatus ? <Button  onClick={addNewTheme} type='primary' className='animate__animated animate__fadeInLeft'>新增</Button>:''
       }
       {
         !props.examineStatus ? <Dropdown overlay={menu}>
         <Button  className='animate__animated animate__fadeInLeft'>
           <Space>
            更多操作
           <DownOutlined />
          </Space>
        </Button>
       </Dropdown>:''
       }
       {
         props.examineStatus ? (
         <>
          <Button  onClick={()=>moreOperation({key:'upperAndLower'})} type='primary' className='animate__animated animate__fadeInLeft'>上下架</Button>
         </>
         ):''
       }
       </div>
       <div>
         <Button  onClick={getNewList} type='primary' className='animate__animated animate__fadeInRight'>查询</Button>
          <Button  type='primary' onClick={resetForm} className='animate__animated animate__fadeInRight'>重置</Button>
          <Button  type='link' onClick={()=>setExpand(i=>!i)} className='animate__animated animate__fadeInRight'>{expand?'收起':'展开'}</Button>
       </div>
    </div>

    <Divider />
    {/* 表格 */}
    <LlxTable
     loading={loading} 
     pagination={pagination}
     setPagination={setPagination}
     selectedRowShow={true}
     rowSelection={rowSelection.current}
     height={!expand?310:420}
     total={total}
     getNewList={getNewList}
     columns={columns}
     dataSource={dataSource}/>

     {/* 弹框 */}
     <AddTheme getNewList={getNewList} dictionaries={dictionaries} userName={props.userInfo.user.userName}  isModalVisible={isModalVisible} setIsModalVisible={setIsModalVisible}></AddTheme>
     {/* 任务分配 */}
     <TaskAllocation  editHttp={editThemeBatch} type={'LESSON'} statusType={'lessonStatus'}  userName={props.userInfo.user.userName} getNewList={getNewList} UserSpecies={dictionaries.UserSpecies} list={selectData} isModalVisible={isModalVisibleTask} setIsModalVisible={setIsModalVisibleTask} ></TaskAllocation>
     {/* 状态变更 */}
     <ChangeStatus http={editThemeStatusBatch} type={'LESSON'} statusType={'lessonStatus'}  userName={props.userInfo.user.userName} getNewList={getNewList} labelOption={dictionaries.Label} list={selectData} isModalVisible={isModalVisibleStatus} setIsModalVisible={setIsModalVisibleStatus} ></ChangeStatus>
 
    {/* 预览 */}
     <PreviewWordSubject type={'theme'} id={id} isModalVisible={isModalVisiblePreview} setIsModalVisible={setIsModalVisiblePreview}></PreviewWordSubject>
  </div>
}

// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data))
  }
}

export default connect((state)=>{
  return {userBtnRole:state.userBtnRole,tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(ThemeLibrary)
